package net.wofly.right.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import net.wofly.common.util.GeneralHelper;
import net.wofly.right.domain.User;
import net.wofly.right.dto.CustomDto;
import net.wofly.right.dto.RepeatCustomerDto;
import net.wofly.right.service.IOrganizationService;
import net.wofly.right.service.IUserService;
import net.wofly.right.util.ReadExcel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.Customer;
import net.wofly.right.repository.CustomerRepository;
import net.wofly.right.service.ICustomerService;
import net.wofly.right.util.RoleEnum;
import org.springframework.web.multipart.MultipartFile;

@Service("iCustomerService")
@Transactional
public class CustomerServiceImpl implements ICustomerService {
	
	@Autowired
	CustomerRepository customerRepository ;
	@Autowired
	IOrganizationService iOrganizationService;
	@Autowired
	IUserService iUserService;

	@Override
	public Customer findOne(String userID) {
		return customerRepository.findOne(userID) ;
	}

	@Override
	public List<Customer> findAll() {
		return (List<Customer>) customerRepository.findAll();
	}

	@Override
	public List<Customer> getCustomerForOrder(String orderType, String salesUserID) {
		switch (orderType) {
			case "1" :
				return findByUserType(1) ;
//				return findAll();
			case "2" :
				return findByUserType(1) ;
//				return findByOrganizationTypeNotIn(returnOrganiztionTypes());
			case "3" :
				return findByOrganizationTypeAndFollowUserID(RoleEnum.流通客户.getValue(), salesUserID);
			case "4" :
				return findByOrganizationTypeAndFollowUserID(RoleEnum.酒店客户.getValue(), salesUserID);
			case "5" :
				return findByOrganizationTypeAndFollowUserID(RoleEnum.签单客户.getValue(), salesUserID);
			case "6" :
				return findByUserType(1) ;
//				return findByOrganizationTypeNotIn(returnOrganiztionTypes());
			case "7" :
				return findByOrganizationTypeAndFollowUserID(RoleEnum.流通客户.getValue(), salesUserID);
			case "8" :
				return findByOrganizationTypeAndFollowUserID(RoleEnum.酒店客户.getValue(), salesUserID);
			case "9" :
				return null;
			case "10" :
				return findByUserType(1) ;
//				return findAll();
			default:
				return null;
		}
	}

	private List<String> returnOrganiztionTypes(){
		List<String> organiztionTypes = new ArrayList<>(2);
		organiztionTypes.add(RoleEnum.流通客户.getValue());
		organiztionTypes.add(RoleEnum.酒店客户.getValue());
		organiztionTypes.add(RoleEnum.签单客户.getValue());
		return organiztionTypes;
	}

	private List<Customer> findByOrganizationTypeAndFollowUserID(String organizationType, String followUserID) {
		return customerRepository.findByOrganizationTypeAndFollowUserID(organizationType, followUserID);
	}

	private List<Customer> findByOrganizationTypeNotIn(List<String> organiztionTypes) {
		return customerRepository.findByOrganizationTypeNotIn(organiztionTypes);
	}
	
	private List<Customer> findByUserType(Integer userType) {
		return customerRepository.findByUserType(userType);
	}

	@Override
	public ReturnBean<PageWrapper<Customer>> getAllCustomer(String customerName, String linkMan, String mobile,
			String organizationType, Integer pageNum, Integer pageSize) {
		
		Condition condition = new Condition();
	    List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
	    
	    if (null != customerName) {
	    		filterConditions.add(new FilterCondition(customerName, "customerName", ConditionRelate.and.name(), Operation.like.name(), 1)) ;
	    }
	    
	    if (null != linkMan) {
	    		filterConditions.add(new FilterCondition(linkMan, "linkman", ConditionRelate.and.name(), Operation.like.name(), 2)) ;
	    }
	    
	    if (null != mobile) {
	    		filterConditions.add(new FilterCondition(mobile, "mobile", ConditionRelate.and.name(), Operation.like.name(), 3)) ;
	    }
	    
	    if (null != organizationType) {
	    		filterConditions.add(new FilterCondition(organizationType, "organizationType", ConditionRelate.and.name(), Operation.eq.name(), 4)) ;
	    }
	    
	    filterConditions.add(new FilterCondition("1", "userType", ConditionRelate.and.name(), Operation.ge.name(), 5)) ;
	    
	    condition.setFilterCondition(filterConditions);
	    
	    condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Customer.class).getResult();
	    
	    Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.ASC, "customerName"));
	    
	    Page<Customer> page = customerRepository.findAll(condition.getSpecification(), pageable);
		
	    return new ReturnBean<>(ResultCode.SUCCESS, "获取所有的客户列表成功！", PageHelper.toPage(page));
	}

	@Override
	public ReturnBean<String> delCustomer(String customerID) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ReturnBean<String> recoverCustomer(String customerID) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ReturnBean<List<String>> importCustomerExcel(MultipartFile file, String userID) {
		//创建处理EXCEL
		ReadExcel readExcel = new ReadExcel();
		//解析excel，获取客户信息集合。
		List<CustomDto> customList = readExcel.getExcelInfo(file.getOriginalFilename() ,file, userID);

		List<String> repeatCustomers = new ArrayList<>();
		for (int i = 0; i < customList.size(); i++) {
			CustomDto customDto = customList.get(i);
			String mobile = customDto.getMobile();
			int rowNum = i + 3;
			if (!GeneralHelper.isMobile(mobile)) {
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("第")
						.append(rowNum)
						.append("行，手机号：")
						.append(customDto.getMobile())
						.append("，手机号格式不正确！");
				repeatCustomers.add(stringBuilder.toString());
				continue;
			}
			List<User> users = iUserService.findByMobile(customDto.getMobile());
			if (users != null && users.size()>0) {
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("第")
						.append(rowNum)
						.append("行，手机号：")
						.append(customDto.getMobile())
						.append("，客户名称为：")
						.append(customDto.getCustomName())
						.append("的客户已经存在，请删除后再导入！");
				repeatCustomers.add(stringBuilder.toString());
			}
		}
		if (repeatCustomers.size() > 0) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "导入客户列表失败！", repeatCustomers);
		}

//		//迭代添加客户信息（注：实际上这里也可以直接将customerList集合作为参数，在Mybatis的相应映射文件中使用foreach标签进行批量添加。）
//		for(CustomDto customDto : customList){
//			iOrganizationService.saveCustomer(customDto);
//		}
		return new ReturnBean<>(ResultCode.SUCCESS, "导入客户列表成功！");
	}
}
